import { useSyncExternalStore } from "react"

export const useStorage = (key: string, initialValue: unknown) => {

    // 订阅
    const subscribe = (callback: () => void) => {

        // 处理事件
        const handleStorage = (e: StorageEvent) => {
            console.log('触发了 storage：', e);
            callback()
        }
        // 当存储区域（localStorage 或 sessionStorage）被修改时，将触发 storage 事件。
        window.addEventListener('storage', handleStorage)
        return () => {
            window.removeEventListener('storage', handleStorage)
        }
    }

    // 快照（获取值）
    const getSnapshot = () => {
        return localStorage.getItem(key) ? JSON.parse(localStorage.getItem(key)!) : initialValue
    }

    // 
    const result = useSyncExternalStore(subscribe, getSnapshot)

    // 修改
    const setStorage = (value: unknown) => {
        // 修改值
        localStorage.setItem(key, JSON.stringify(value))
        // 需要手动触发 window 的 storage 事件
        window.dispatchEvent(new StorageEvent('storage'))
    }

    return [
        result,
        setStorage
    ]

}
